﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace SuperiorCommon.Request
{
    /// <summary>
    /// http网络请求类
    /// </summary>
    public class HttpRequest
    {
        public static string RequestGet(string url)
        {
            string serviceAddress = url;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = " text/html; charset=utf-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        public static byte[] RequestGet_Image(string url)
        {
            string serviceAddress = url;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
           
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            //string retString = myStreamReader.ReadToEnd();
            var  res = StreamToBytes(myResponseStream);
            myStreamReader.Close();
            myResponseStream.Close();
            return res;
        }

        ///将数据流转为byte[]
        public static byte[] StreamToBytes(Stream stream)
        {
            List<byte> bytes = new List<byte>();
            int temp = stream.ReadByte();
            while (temp != -1)
            {
                bytes.Add((byte)temp);
                temp = stream.ReadByte();
            }
            return bytes.ToArray();
        }
        /// 将 Stream 转成 byte[]


        public static string RequestForPost(string url)
        {
            string strResult = "";
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                try
                {
                    HttpWebResponse HttpWResp = (HttpWebResponse)myRequest.GetResponse();
                    Stream myStream = HttpWResp.GetResponseStream();
                    StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
                    StringBuilder strBuilder = new StringBuilder();
                    while (-1 != sr.Peek())
                    {
                        strBuilder.Append(sr.ReadLine());
                    }
                    strResult = strBuilder.ToString();
                }
                catch (Exception exp)
                {
                    strResult = "错误：" + exp.Message;
                }
            }
            catch (Exception exp)
            {
                strResult = "错误：" + exp.Message;
            }
            return strResult;
        }

        /// <summary>
        /// 转换字节流并调用方法
        /// </summary>
        /// <param name="data"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string PostDataToUrl(string data, string url)
        {
            Encoding encoding = Encoding.GetEncoding("utf-8");

            byte[] bytesToPost = encoding.GetBytes(data);

            return PostDataToUrl(bytesToPost, url);
        }
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开
            return true;
        }

        /// <summary>
        /// 执行链接得到返回信息
        /// </summary>
        /// <param name="data"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private static string PostDataToUrl(byte[] data, string url)
        {
            string stringResponse = string.Empty;

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            #region 创建httpWebRequest对象
            WebRequest webRequest = WebRequest.Create(url);
            HttpWebRequest httpRequest = webRequest as HttpWebRequest;
            #endregion

            #region 填充httpWebRequest的基本信息
            httpRequest.ContentType = "application/json";
            httpRequest.Method = "POST";
            httpRequest.Timeout = 1000 * 1000;

            #endregion


            Stream requestStream = null;
            try
            {
                #region 填充要post的内容
                httpRequest.ContentLength = data.Length;
                requestStream = httpRequest.GetRequestStream();
                requestStream.Write(data, 0, data.Length);
                requestStream.Close();
                #endregion

                #region 发送post请求到服务器并读取服务器返回信息
                Stream responseStream = null;

                try
                {
                    responseStream = httpRequest.GetResponse().GetResponseStream();

                    using (StreamReader responseReader =
                        new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
                    {
                        stringResponse = responseReader.ReadToEnd();
                    }
                    responseStream.Close();
                }
                catch (Exception e)
                {
                    stringResponse = e.Message;
                }
                #endregion

                #region 读取服务器返回信息

                #endregion
            }
            catch { }
            return stringResponse;
        }

    }
}
